package com.rupertjones.globalcron.web.service;

import com.rupertjones.globalcron.domain.Role;
import com.rupertjones.globalcron.domain.dao.RoleDAO;
import com.rupertjones.globalcron.domain.User;
import com.rupertjones.globalcron.domain.dao.UserDAO;
import com.rupertjones.globalcron.util.SecretEncoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;

/**
 * <p>&copy Rupert Jones 2011,2012</p>
 *
 * @author rup
 */
@Service
@Transactional
public class DefaultUserService implements UserService {

    @Autowired
    private UserDAO userDAO;

    @Autowired
    private RoleDAO roleDAO;

    public User findUser(String username) {
        return userDAO.findByUsername(username);
    }

    public void saveWithPassword(User user, String password) {
        user.setPassword(SecretEncoder.hash(password));
        userDAO.upsert(user);
    }

    public Collection<User> findAllUsers() {
        return userDAO.findAll();
    }

    public Collection<Role> findAllRoles() {
        return roleDAO.findAll();
    }

    public Role findRole(String roleName) {
        return roleDAO.findByName(roleName);
    }

    public User findUser(int userId) {
        return userDAO.findById(userId);
    }

    public void save(User actualUser) {
        userDAO.upsert(actualUser);
    }
}

